﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using App.Core.Extensions;
using App.Data;
using System.IO;

public partial class Pages_Admin_AdvertisementChange : BasePage
{
    private int _ID = 0;
    private bool _IsEditMode = false;

    protected void Page_Load(object sender, EventArgs e)
    {
        BindPageInfo();
        if (!IsPostBack)
        {
            BindDropDownLists();
            BindAdvertisementInfo();            
        }
    }
    /// <summary>
    /// Bindis the Page Initialization Variables
    /// </summary>
    protected void BindPageInfo()
    {
        _ID = WebUtil.GetQueryStringInInt(AppConstants.QueryString.ID);
        if (_ID > 0)
        {
            _IsEditMode = true;
            h4Heading.InnerHtml = "Edit Advertisement";
            rfvFileName.Enabled = false;
        }
        Page.Title = WebUtil.GetPageTitle(h4Heading.InnerHtml);
    }

    /// <summary>
    /// Binds Dropdownlists for the initial request.
    /// </summary>
    protected void BindDropDownLists()
    {
        BindDropdownList.Customers(ddlCustomerID);
        //BindDropdownList.Users(ddlModifiedBy);
    }
    /// <summary>
    /// Binds Advertisement Info Requested through Query Strings
    /// </summary>
    
    protected void BindAdvertisementInfo()
    {
        if (_IsEditMode)
        {
            BtcHousingEntities context = new BtcHousingEntities();
            Advertisement entity = context.Advertisements.FirstOrDefault(P => P.ID == _ID);//dao.GetByID(_ID);
            if (entity == null)
                ShowErrorMessage();
            else
            {
                ddlCustomerID.SetSelectedItem(entity.CustomerID.ToString());
                txtName.Text = entity.Name;
                txtLinkedUrl.Text = entity.LinkedUrl;
                rdblFileType.SetSelectedItem(entity.FileType);
                ///TODO: Need add Image or Flash according to the selection
                if (String.Compare(entity.FileType, "I", true) == 0)
                {   
                    divAddPreviewContainer.InnerHtml = String.Format("<img class='AdverstisementImage' src='{0}/{1}' alt='' title='' />", AppConstants.ADVERTISEMENT_FILES, entity.FileName);
                    divAddPreviewContainer.Visible = true;
                }

                if (String.Compare(entity.FileType, "F", true) == 0)
                {
                    divAddPreviewContainer.InnerHtml = String.Format("<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0' width='200' height='auto'> <param name='movie' value='{0}/{1}' /> <param name='quality' value='high' /> <embed src='{0}/{1}' quality='high' pluginspage='http://www.macromedia.com/go/getflashplayer' type='application/x-shockwave-flash' width='200' height='auto'> </embed> </object>", AppConstants.ADVERTISEMENT_FILES, entity.FileName);
                    divAddPreviewContainer.Visible = true;
                }
                txtSortOrder.Text = entity.SortOrder.ToString() ;
                chkIsActive.Checked = entity.IsActive;
                rdblPosition.SetSelectedItem(entity.Position);
                chkIsHomePageBanner.Checked = entity.IsHomePageBanner;
                //chkIsDeleted.Checked = entity.IsDeleted;
            }
        }
    }

    protected void ShowSuccessMessage()
    {
        if (String.Compare(WebUtil.GetQueryStringInString(AppConstants.QueryString.SUCCESS_MESSAGE), "True", false) == 0)
        {
            WebUtil.ShowMessageBox(divMessage, "Advertisement Saved Successfully.", false);
        }
    }
    /// <summary>
    /// Shows a Message in the UI and Hides the Data Editing Controls
    /// </summary>
    protected void ShowErrorMessage()
    {
        pnlFormContainer.Visible = false;
        WebUtil.ShowMessageBox(divMessage, "Requested Advertisement was not found.", true);
    }
    protected void SaveAdvertisement()
    {
        BtcHousingEntities context = new BtcHousingEntities();
        Advertisement entity = null;

        if (_IsEditMode)
            entity = context.Advertisements.FirstOrDefault(P => P.ID == _ID); //dao.GetByID(_ID);        
        else
        {
            entity = new Advertisement();
            entity.FileName = "N/A";
            entity.Created = DateTime.Now;
            context.AddToAdvertisements(entity);
        }

        entity.CustomerID = ddlCustomerID.SelectedValue.ToInt();
        entity.Name = txtName.Text;
        entity.LinkedUrl = txtLinkedUrl.Text;
        entity.FileType = rdblFileType.SelectedValue;
        if(_IsEditMode && fuFile.HasFile)
            entity.FileName = SaveAdvertisementFile(entity);

        entity.SortOrder = txtSortOrder.Text.ToInt();
        entity.IsActive = chkIsActive.Checked;
        entity.Position = rdblPosition.SelectedValue;
        entity.Modified = DateTime.Now;
        entity.ModifiedBy = SessionCache.CurrentUser.ID;
        entity.IsHomePageBanner = chkIsHomePageBanner.Checked;
        entity.IsDeleted = false;
        context.SaveChanges();

        if (!_IsEditMode)
        {
            entity.FileName = String.Empty;
            entity.FileName = SaveAdvertisementFile(entity);
            context.SaveChanges();
        }
        _ID = entity.ID;
        
        WebUtil.ShowMessageBox(divMessage, "Advertisement Saved Successfully.", false);
    }

    private string SaveAdvertisementFile(Advertisement entity)
    {
        String fileDirectory = Server.MapPath(AppConstants.ADVERTISEMENT_FILES);
        if (_IsEditMode)
        {
            ///Delete Existing File
            if (!entity.FileName.IsNullOrEmpty())
            {
                String filePath = Path.Combine(fileDirectory, entity.FileName);
                if (File.Exists(filePath))
                    File.Delete(filePath);
            }
        }

        if (!Directory.Exists(fileDirectory))
            Directory.CreateDirectory(fileDirectory);

        String outputFileName = Path.Combine(fileDirectory, String.Format("{0}_{1}", entity.ID, Path.GetFileName(fuFile.PostedFile.FileName)));

        if ( String.Compare(entity.FileType, "I", true) == 0 ){ // Image File
            String inputFileName = Path.Combine(Server.MapPath(AppConstants.TEMP_DIRECTORY), String.Format("{0}{1}", System.Guid.NewGuid().ToString(), Path.GetExtension(fuFile.PostedFile.FileName)));
            WebUtil.GenerateThumbnail(inputFileName, outputFileName, ConfigReader.AdvertisementWidth, true);
            fuFile.SaveAs(inputFileName);
        }else    
            fuFile.SaveAs(outputFileName); // Flash File
 
        return Path.GetFileName(outputFileName);
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            SaveAdvertisement();
            //Response.Redirect(String.Format("{0}?{1}={2}&{3}=True", AppConstants.Pages.ADVERTISEMENT_CHANGE, AppConstants.QueryString.ID, _ID, AppConstants.QueryString.SUCCESS_MESSAGE));
            //Response.Redirect(Request.Url.AbsolutePath);
            Response.Redirect(AppConstants.Pages.ADVERTISEMENT_LIST);
            return;
        }
    }
    protected void btnList_Click(object sender, EventArgs e)
    {
        Response.Redirect("AdvertisementList.aspx");
        return;
    }
    protected void cvFileName_OnServerValidate(object sender, ServerValidateEventArgs e)
    {
        if (fuFile.HasFile)
        {
            if (WebUtil.IsValidImageFile(fuFile.PostedFile) || WebUtil.IsValidFlashFile(fuFile.PostedFile))
                e.IsValid = true;
            else
                e.IsValid = false;
        }
        //if (_IsEditMode && !fuFile.HasFile)
        //    e.IsValid = true;
        //else
        //    e.IsValid = false;
    }
}